package com.puman.watchtrade.util;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.activation.MimetypesFileTypeMap;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class FileUpload {

	/**
	 * 上传图片
	 * 
	 * @param urlStr
	 * @param textMap
	 * @param fileMap
	 * @return
	 */
	public static String formUpload1(String urlStr,
			Map<String, String> textMap, List<String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY)
							.append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				if (fileMap.size() > 0) {
					// Iterator iter = fileMap.entrySet().iterator();
					for (int i = 0; i < fileMap.size(); i++) {
						String inputName = "files";
						String inputValue = fileMap.get(i);
						if (inputValue == null) {
							continue;
						}
						File file = new File(inputValue);
						String filename = file.getName();
						String contentType = new MimetypesFileTypeMap()
								.getContentType(file);
						if (filename.endsWith(".png")) {
							contentType = "image/png";
						}
						if (contentType == null || contentType.equals("")) {
							contentType = "application/octet-stream";
						}

						StringBuffer strBuf = new StringBuffer();
						strBuf.append("\r\n").append("--").append(BOUNDARY)
								.append("\r\n");
						strBuf.append("Content-Disposition: form-data; name=\""
								+ inputName + "\"; filename=\"" + filename
								+ "\"\r\n");
						strBuf.append("Content-Type:" + contentType
								+ "\r\n\r\n");

						out.write(strBuf.toString().getBytes());

//						DataInputStream in = new DataInputStream(
//								new FileInputStream(file));
						Log.i("curry", "file size:"+file.length()/1024);
						Bitmap bmp = compressImageFromFile(inputValue);
//						Bitmap bmp = BitmapFactory.decodeFile(inputValue);
//								ByteArrayOutputStream bos = new ByteArrayOutputStream();
//								bmp.compress(CompressFormat.JPEG, 70, bos);
//								InputStream inData = new ByteArrayInputStream(bos.toByteArray());
						InputStream in = Bitmap2InputStream(bmp);
						int bytes = 0;
						int sum = 0;
						byte[] bufferOut = new byte[1024];
						while ((bytes = in.read(bufferOut)) != -1) {
							out.write(bufferOut, 0, bytes);
							sum += bytes;
						}
						
						in.close();
					}
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			System.out.println("发送POST请求出错。" + urlStr);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
	}
	
	public static InputStream Bitmap2InputStream(Bitmap bm) {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
	    InputStream is = new ByteArrayInputStream(baos.toByteArray());
	    return is;
	    }
	 private static Bitmap compressImageFromFile(String srcPath) {  
	        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
	        newOpts.inJustDecodeBounds = true;//只读边,不读内容  
	        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
	  
	        newOpts.inJustDecodeBounds = false;  
	        int w = newOpts.outWidth;  
	        int h = newOpts.outHeight;  
	        float hh = 480f;//  
	        float ww = 320f;//  
	        int be = 1;  
	        if (w > h && w > ww) {  
	            be = (int) (newOpts.outWidth / ww);  
	        } else if (w < h && h > hh) {  
	            be = (int) (newOpts.outHeight / hh);  
	        }  
	        if (be <= 0)  
	            be = 1;  
	        newOpts.inSampleSize = be;//设置采样率  
	          
	        newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设  
	        newOpts.inPurgeable = true;// 同时设置才会有效  
	        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收  
	          
	        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
//	      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩  
	                                    //其实是无效的,大家尽管尝试  
	        return bitmap;  
	    }  
	public static String formUpload(String urlStr, Map<String, String> textMap,
			List<String> fileMap) {
		String res = "";
		HttpURLConnection conn = null;
		String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY)
							.append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			Log.i("curry", "fileMap brfore");
			if (fileMap != null) {
				Log.i("curry", "fileMap size:"+fileMap.size());
				if (fileMap.size() > 0) {
					// Iterator iter = fileMap.entrySet().iterator();
					for (int i = 0; i < fileMap.size(); i++) {
						String inputName = "files";
						String inputValue = fileMap.get(i);
						Log.i("curry", "inputValue:"+inputValue);
						if (inputValue == null) {
							continue;
						}
						File file = new File(inputValue);
						String filename = file.getName();
//						Log.i("curry", "filename:"+filename);
						String contentType = "image/jpeg";

						StringBuffer strBuf = new StringBuffer();
						strBuf.append("\r\n").append("--").append(BOUNDARY)
								.append("\r\n");
						strBuf.append("Content-Disposition: form-data; name=\""
								+ inputName + "\"; filename=\"" + filename
								+ "\"\r\n");
						strBuf.append("Content-Type:" + contentType
								+ "\r\n\r\n");

						out.write(strBuf.toString().getBytes());
						Log.i("curry", "out:write");
//						DataInputStream in = new DataInputStream(
//								new FileInputStream(file));
//						Log.i("curry", "file size:"+file.length()/1024);
						Bitmap bmp = sampleImageFromFile(inputValue, 480, 800);
//						Bitmap bmp = BitmapFactory.decodeFile(inputValue);
//								ByteArrayOutputStream bos = new ByteArrayOutputStream();
//								bmp.compress(CompressFormat.JPEG, 70, bos);
//								InputStream inData = new ByteArrayInputStream(bos.toByteArray());
						InputStream in = Bitmap2InputStream(bmp, 70);
						Log.i("curry", "InputStream");
						int bytes = 0;
						int sum = 0;
						byte[] bufferOut = new byte[1024];
						while ((bytes = in.read(bufferOut)) != -1) {
							out.write(bufferOut, 0, bytes);
							sum += bytes;
						}
						Log.i("curry", "sum:"+sum);
						in.close();
					}
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
			System.out.println("发送POST请求出错。" + urlStr);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return res;
		}
	
	public static InputStream Bitmap2InputStream(Bitmap bm, int compressPercent) {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    bm.compress(Bitmap.CompressFormat.JPEG, compressPercent, baos);
	    InputStream is = new ByteArrayInputStream(baos.toByteArray());
	    return is;
	    }
	
	 private static Bitmap sampleImageFromFile(String srcPath, float h2, float w2) {  
	        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
	        newOpts.inJustDecodeBounds = true;//只读边,不读内容  
	        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
	  
	        newOpts.inJustDecodeBounds = false;  
	        int w = newOpts.outWidth;  
	        int h = newOpts.outHeight;  
	        float hh = h2;//  
	        float ww = w2;//  
	        int be = 1;  
	        if (w > h && w > ww) {  
	            be = (int) (newOpts.outWidth / ww);  
	        } else if (w < h && h > hh) {  
	            be = (int) (newOpts.outHeight / hh);  
	        }  
	        if (be <= 0)  
	            be = 1;  
	        newOpts.inSampleSize = be;//设置采样率  
	          
	        newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设  
	        newOpts.inPurgeable = true;// 同时设置才会有效  
	        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收  
	          
	        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
//	      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩  
	                                    //其实是无效的,大家尽管尝试  
	        return bitmap;  
	    }  
	 
}
